import time
import requests

from web3 import Web3
from web3.middleware import geth_poa_middleware
from contracts.node_registry import CONTRACT_ADDRESS, ABI

w3 = Web3(Web3.HTTPProvider("http://172.27.244.201:8546"))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)

node_address = w3.eth.accounts[0]

contract = w3.eth.contract(address=CONTRACT_ADDRESS, abi=ABI)
tx = contract.functions.registerNode().transact({"from": node_address, "nonce": w3.eth.get_transaction_count(node_address)})
w3.eth.wait_for_transaction_receipt(tx)

def send_heartbeat():
    try:
        requests.post('http://127.0.0.1:5000/heartbeat', json={'node_address': node_address})
        print("Heartbeat sent")
    except Exception as e:
        print(f"Failed to send heartbeat: {e}")



while True:
    send_heartbeat()
    time.sleep(60)  # 每分钟发送一次心跳信号